/*
 * DiABluUI.java
 *
 * Created on 12 de Abril de 2006, 9:05
 */

package citar.diablu.gui;

import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.*;
import java.nio.channels.*;
import de.sciss.net.*;

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import citar.diablu.classes.*;
import citar.diablu.bc.DiABluBC;
import citar.diablu.com.interfaces.*;

/**
 *
 * @author  nrodrigues
 */
public class DiABluUI extends javax.swing.JFrame {
    
    // Business core class
    DiABluBC DBbc;
    
    // Default Values
    int DEFAULT_DELAY = 10000;      // delay between bt inquirys
    
    /**
     * Creates new form DiABluUI
     */
    public DiABluUI(DiABluBC ourDBbc) {
        
        System.out.println("DiABlu UI is rising...");    
        
        // DiABlu Business Core Class
        DBbc = ourDBbc;
        
        // Initialize graphics components
        initComponents();
        setVisible(true);
      
        // Customize components parameters

    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        sim_jp = new javax.swing.JPanel();
        uuid_jl = new javax.swing.JLabel();
        uuid_jtf = new javax.swing.JTextField();
        friendly_jl = new javax.swing.JLabel();
        friendly_jtf = new javax.swing.JTextField();
        add_jb = new javax.swing.JButton();
        edit_jb = new javax.swing.JButton();
        remove_jb = new javax.swing.JButton();
        message_jl = new javax.swing.JLabel();
        gaction_jcb = new javax.swing.JComboBox();
        sendKeys_jb = new javax.swing.JButton();
        key_jcb = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        messagein_jtf = new javax.swing.JTextField();
        sendTextMsg_jb = new javax.swing.JButton();
        settings_jp = new javax.swing.JPanel();
        service_jl = new javax.swing.JLabel();
        service_jtf = new javax.swing.JTextField();
        adress_jl = new javax.swing.JLabel();
        adress_jtf = new javax.swing.JTextField();
        port_jl = new javax.swing.JLabel();
        port_jtf = new javax.swing.JTextField();
        delay_jl = new javax.swing.JLabel();
        delay_jtf = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        detected_jp = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        detectedTable_jt = new javax.swing.JTable();
        log_jp = new javax.swing.JPanel();
        log_jsp = new javax.swing.JScrollPane();
        log_jta = new javax.swing.JTextArea();
        clearLog_jb = new javax.swing.JButton();
        logDetail_jl = new javax.swing.JLabel();
        comboLog = new javax.swing.JComboBox();
        menubar_jmb = new javax.swing.JMenuBar();
        about_jm = new javax.swing.JMenu();
        credits_jmi = new javax.swing.JMenuItem();
        exit_jm = new javax.swing.JMenu();
        exit_jmi = new javax.swing.JMenuItem();

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("DiABlu Server 1(build 72)");
        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 230, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 0, Short.MAX_VALUE)
        );

        sim_jp.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Simulated Devices", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), java.awt.Color.blue));
        uuid_jl.setText("UUID:");

        uuid_jtf.setText("08002B0ECEF1");

        friendly_jl.setText("Friendly Name:");

        friendly_jtf.setText("JC's PDA");

        add_jb.setText("Add");
        add_jb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                add_jbActionPerformed(evt);
            }
        });

        edit_jb.setText("Edit");
        edit_jb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edit_jbActionPerformed(evt);
            }
        });

        remove_jb.setText("Remove");
        remove_jb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                remove_jbActionPerformed(evt);
            }
        });

        message_jl.setText("Game Action:");

        gaction_jcb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "[none]", "UP", "DOWN", "LEFT", "RIGHT", "FIRE", "GAME_A", "GAME_B", "GAME_C", "GAME_D" }));

        sendKeys_jb.setText("Send");
        sendKeys_jb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendKeys_jbActionPerformed(evt);
            }
        });

        key_jcb.setEditable(true);
        key_jcb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "KEY_STAR", "KEY_POUND", "KEY_NUM0", "KEY_NUM1", "KEY_NUM2", "KEY_NUM3", "KEY_NUM4", "KEY_NUM5", "KEY_NUM6", "KEY_NUM7", "KEY_NUM8", "KEY_NUM9", "[none]" }));

        jLabel1.setText(" Key:");

        jLabel2.setText("[Messaging]");

        jLabel4.setText("Text Message:");

        messagein_jtf.setText("Type here a simple text message...");

        sendTextMsg_jb.setText("Send");
        sendTextMsg_jb.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                sendTextMsg_jbMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout sim_jpLayout = new org.jdesktop.layout.GroupLayout(sim_jp);
        sim_jp.setLayout(sim_jpLayout);
        sim_jpLayout.setHorizontalGroup(
            sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(sim_jpLayout.createSequentialGroup()
                .addContainerGap()
                .add(sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(uuid_jl)
                    .add(friendly_jl)
                    .add(jLabel2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, sim_jpLayout.createSequentialGroup()
                        .add(uuid_jtf, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(add_jb)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(edit_jb)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(remove_jb))
                    .add(friendly_jtf, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                    .add(sim_jpLayout.createSequentialGroup()
                        .add(sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(message_jl)
                            .add(jLabel4))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(sim_jpLayout.createSequentialGroup()
                                .add(messagein_jtf, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(sendTextMsg_jb))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, sim_jpLayout.createSequentialGroup()
                                .add(gaction_jcb, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 79, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(jLabel1)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(key_jcb, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 249, Short.MAX_VALUE)
                                .add(sendKeys_jb)))))
                .addContainerGap())
        );
        sim_jpLayout.setVerticalGroup(
            sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(sim_jpLayout.createSequentialGroup()
                .add(sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(friendly_jl)
                    .add(friendly_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(uuid_jl)
                    .add(remove_jb)
                    .add(edit_jb)
                    .add(add_jb)
                    .add(uuid_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(jLabel4)
                    .add(sendTextMsg_jb)
                    .add(messagein_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(sim_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(sendKeys_jb)
                    .add(message_jl)
                    .add(gaction_jcb, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1)
                    .add(key_jcb, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        settings_jp.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Settings", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), java.awt.Color.blue));
        service_jl.setText("Service Name:");

        service_jtf.setText("DiABlu666");

        adress_jl.setText("Target Address:");

        adress_jtf.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        adress_jtf.setText("127.0.0.1");

        port_jl.setText("Port:");

        port_jtf.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        port_jtf.setText("10000");

        delay_jl.setText("Delay between bluetooth discoverys(ms):");

        delay_jtf.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        delay_jtf.setText("10000");
        delay_jtf.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                delay_jtfPropertyChange(evt);
            }
        });

        jLabel5.setText("[bluetooth]");

        jLabel6.setText("[osc]");

        org.jdesktop.layout.GroupLayout settings_jpLayout = new org.jdesktop.layout.GroupLayout(settings_jp);
        settings_jp.setLayout(settings_jpLayout);
        settings_jpLayout.setHorizontalGroup(
            settings_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, settings_jpLayout.createSequentialGroup()
                .add(22, 22, 22)
                .add(settings_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel5)
                    .add(jLabel6))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 13, Short.MAX_VALUE)
                .add(settings_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(adress_jl)
                    .add(service_jl))
                .add(4, 4, 4)
                .add(settings_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, settings_jpLayout.createSequentialGroup()
                        .add(service_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 254, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(delay_jl))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, settings_jpLayout.createSequentialGroup()
                        .add(adress_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(port_jl)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(settings_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, port_jtf)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, delay_jtf, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE))
                .addContainerGap())
        );
        settings_jpLayout.setVerticalGroup(
            settings_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(settings_jpLayout.createSequentialGroup()
                .addContainerGap()
                .add(settings_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(delay_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(delay_jl)
                    .add(service_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(service_jl)
                    .add(jLabel5))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(settings_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(port_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(port_jl)
                    .add(jLabel6)
                    .add(adress_jl)
                    .add(adress_jtf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        detected_jp.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Detected Devices", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), java.awt.Color.blue));
        detectedTable_jt.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "UUID  ", "Friendly Name", "Device Type", "Last Msg", "Last Key"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        detectedTable_jt.getColumnModel().getColumn(0).setPreferredWidth(310);
        detectedTable_jt.getColumnModel().getColumn(1).setPreferredWidth(400);
        detectedTable_jt.getColumnModel().getColumn(2).setPreferredWidth(80);
        detectedTable_jt.getColumnModel().getColumn(3).setPreferredWidth(120);
        //detectedTable_jt.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //Ask to be notified of selection changes.
        ListSelectionModel rowSM = detectedTable_jt.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                //Ignore extra messages.
                if (e.getValueIsAdjusting()) return;

                ListSelectionModel lsm =
                (ListSelectionModel)e.getSource();
                if (lsm.isSelectionEmpty()) {
                    //no rows are selected
                } else {
                    int selectedRow = lsm.getMinSelectionIndex();
                    //selectedRow is selected
                    setUUID(detectedTable_jt.getValueAt(selectedRow,0).toString());
                    setFName(detectedTable_jt.getValueAt(selectedRow,1).toString());
                }
            }
        });
        jScrollPane1.setViewportView(detectedTable_jt);

        org.jdesktop.layout.GroupLayout detected_jpLayout = new org.jdesktop.layout.GroupLayout(detected_jp);
        detected_jp.setLayout(detected_jpLayout);
        detected_jpLayout.setHorizontalGroup(
            detected_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(detected_jpLayout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 669, Short.MAX_VALUE)
                .addContainerGap())
        );
        detected_jpLayout.setVerticalGroup(
            detected_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(detected_jpLayout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)
                .addContainerGap())
        );

        log_jp.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Log", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), java.awt.Color.blue));
        log_jta.setColumns(20);
        log_jta.setRows(5);
        log_jsp.setViewportView(log_jta);

        clearLog_jb.setText("Clear ");
        clearLog_jb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearLog_jbActionPerformed(evt);
            }
        });

        logDetail_jl.setText("Log Detail:");

        comboLog.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Simple", "Detailed", "Errors only" }));

        org.jdesktop.layout.GroupLayout log_jpLayout = new org.jdesktop.layout.GroupLayout(log_jp);
        log_jp.setLayout(log_jpLayout);
        log_jpLayout.setHorizontalGroup(
            log_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(log_jpLayout.createSequentialGroup()
                .addContainerGap()
                .add(log_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(log_jpLayout.createSequentialGroup()
                        .add(logDetail_jl)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(comboLog, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 473, Short.MAX_VALUE)
                        .add(clearLog_jb))
                    .add(log_jsp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 669, Short.MAX_VALUE))
                .addContainerGap())
        );
        log_jpLayout.setVerticalGroup(
            log_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, log_jpLayout.createSequentialGroup()
                .add(log_jsp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(log_jpLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(comboLog, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(logDetail_jl)
                    .add(clearLog_jb))
                .addContainerGap())
        );

        about_jm.setText("About");
        about_jm.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                about_jmActionPerformed(evt);
            }
        });

        credits_jmi.setText("About");
        credits_jmi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                credits_jmiActionPerformed(evt);
            }
        });

        about_jm.add(credits_jmi);

        menubar_jmb.add(about_jm);

        exit_jm.setText("Exit");
        exit_jm.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exit_jmActionPerformed(evt);
            }
        });

        exit_jmi.setText("Exit");
        exit_jmi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exit_jmiActionPerformed(evt);
            }
        });

        exit_jm.add(exit_jmi);

        menubar_jmb.add(exit_jm);

        setJMenuBar(menubar_jmb);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(settings_jp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, sim_jp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(detected_jp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(471, 471, 471)
                        .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .add(log_jp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(detected_jp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(sim_jp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(settings_jp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(log_jp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void delay_jtfPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_delay_jtfPropertyChange
// TODO add your handling code here:
    }//GEN-LAST:event_delay_jtfPropertyChange

    private void sendTextMsg_jbMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sendTextMsg_jbMouseClicked
       
        // get the target address & port
        InetSocketAddress addr = getSocketAddress();
        
        // get  the DiABlu Message
        DiABluMsg msgin = getTextMessage();
        
        // send the message 
        DBbc.sendMsg(msgin,addr);
        
        // Log - debug mode only since the log is processed in DBbc class
        //newLog(0,"[Send Text Message]:"+msgin.getText());
                     
    }//GEN-LAST:event_sendTextMsg_jbMouseClicked

    private void clearLog_jbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearLog_jbActionPerformed
        
        log_jta.setText("");
    }//GEN-LAST:event_clearLog_jbActionPerformed

    private void sendKeys_jbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendKeys_jbActionPerformed
        
        newLog(0,"[SIMULATED MESSAGING]Processing Keys...");
               
        // Data collect: get the game action & key code
        String gActionT = getGAction();
        String sKeyT = getKeyPressed();
        
        // VALIDATION:No key or game action selected
        if ( gActionT.equalsIgnoreCase("[none]") && sKeyT.equalsIgnoreCase("[none]")) {
            newLog(1,"ERROR!Don't know what to send.Please input a Key or a Game Action to send.");
            return;
        }
        
        // Data collect: get the id & target address
        String fnameT = getFName();
        String uuidT = getUUID();                
        InetSocketAddress addr = getSocketAddress();
        
        // Format the data
        DiABluID DBid = new DiABluID(uuidT,fnameT);
        DiABluKey DBkey = new DiABluKey(DBid,sKeyT,gActionT);
                        
        // Send the keys 
        DBbc.sendKeys(DBkey,addr);
        
        newLog(0,"[SIMULATED MESSAGING]Keys sended to Business Core...");
            
    }//GEN-LAST:event_sendKeys_jbActionPerformed

    private void remove_jbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remove_jbActionPerformed
                                       
        // Create & initialize the temporary variables needed
        String uuidT = "";
        String fnameT = "";
        DiABluDevice DBdvT = null;
        DiABluID DBidT = null;
        Vector dDevicesRemove = new Vector();
        Vector dDevicesList = new Vector();
               
        // Get the target address
        InetSocketAddress addr = getSocketAddress();
        
        // VALIDATION:Check that we have at least one row selected
        if ( detectedTable_jt.getSelectedRow() == -1 ) {
            newLog(1,"ERROR!Please select one or more rows to remove");
            return;
        } else {                                                
            
            // Get the table model
            DefaultTableModel modelT = (DefaultTableModel) detectedTable_jt.getModel();
            
            // Check for single or multiple selection
            if ( detectedTable_jt.getSelectedRowCount() == 1 ) {
                
                // We only have one row to eliminate
                // We need to get the data in order to send it to /deviceout
                uuidT = modelT.getValueAt(detectedTable_jt.getSelectedRow(),0).toString();
                fnameT = modelT.getValueAt(detectedTable_jt.getSelectedRow(),1).toString();
                newLog(0,"[REMOVE SIMULATED DEVICE]Removing the device...");          
                //modelT.removeRow(detectedTable_jt.getSelectedRow());                
                
                // Create the corresponding DiABlu Device to be removed
                DBidT = new DiABluID(uuidT,fnameT);
                DBdvT = new DiABluDevice(DBidT);
                
                // Add the device to the Vector of removed devices
                dDevicesRemove.addElement(DBdvT);
         
                newLog(0,"[REMOVE SIMULATED DEVICES]UUID:"+uuidT+"|FNAME:"+fnameT);
                
            } else {
                    // We have multiple remove selections                    
                    int mRemove = detectedTable_jt.getSelectedRowCount();
                    // Let's get the index of them all
                    int[] mR = new int[mRemove];
                    mR = detectedTable_jt.getSelectedRows();
                    newLog(0,"[REMOVE SIMULATED DEVICES]Selected "+ mRemove +" devices...");
                
                    for (int i=0; i < mRemove; i++){
                    
                        // We need to colect the data in order to send it to /devicesout
                        uuidT = modelT.getValueAt(mR[i],0).toString();
                        fnameT = modelT.getValueAt(mR[i],1).toString();
                        
                        // Create the corresponding DiABlu Device to be removed
                        DBidT = new DiABluID(uuidT,fnameT);
                        DBdvT = new DiABluDevice(DBidT);
                
                        // Add the device to the Vector of removed devices
                        dDevicesRemove.addElement(DBdvT);                                                               
                        
                        // Remove the device from the UI tablemodel
                        //modelT.removeRow(detectedTable_jt.getSelectedRow());
                    
                    }                
                    
                }
                
                // Update the tabel model
                newLog(0,"[REMOVE SIMULATED DEVICES]Updating table model..."); 
                //detectedTable_jt.setModel( (TableModel) modelT );
            
                /**
                 * Now we need to update de OSC 
                 * Send the removed devices [DEVICEOUT][DEVICESOUT]
                 * Update the device counter [DEVICECOUNT]
                 * Update the device list    [DEVICESLIST]
                 *
                 */                                                               
                
                newLog(0,"[REMOVE SIMULATED DEVICES]Sending OSC Information...");
                
                // Send the list of removed devices
                newLog(0,"[DiABluUI-remove_jb()]Sending list("+dDevicesRemove.size()+") of devices to be removed");
                
                for (int i=0;i<dDevicesRemove.size();i++){
                    uuidT=((DiABluDevice)dDevicesRemove.elementAt(i)).getID().getUUID();
                    fnameT=((DiABluDevice)dDevicesRemove.elementAt(i)).getID().getFName();
                    newLog(0,"[DiABluUI-remove_jb()]Device:"+fnameT+"@"+uuidT);
                }
                
                DBbc.sendRemoveDevices(dDevicesRemove,addr);
                newLog(0,"[REMOVE SIMULATED DEVICE][OSC /device(s)out]:"+ dDevicesRemove.size());
                
                // Update counter
                int dc = detectedTable_jt.getRowCount();                    
                DBbc.sendDeviceCount(dc,addr);                
                newLog(0,"[REMOVE SIMULATED DEVICE][OSC /devicecount]:"+ dc );
                
                // Update devicelist
                dDevicesList = modelTOvector (detectedTable_jt.getModel());
                DBbc.sendDeviceList(dDevicesList, addr);
                newLog(0,"[REMOVE SIMULATED DEVICES]Updating list /devicelist");                                            
                
        }
    }//GEN-LAST:event_remove_jbActionPerformed

    private void edit_jbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edit_jbActionPerformed
        
        // TODO: What about nothing was changed ? Check for this.
        Vector dDevicesList = new Vector();          // DiABlu Devices List to be send at the end
        InetSocketAddress addr = getSocketAddress(); // Get the target address
        
        if ( detectedTable_jt.getSelectedRow() == -1 ) {
            newLog(1,"ERROR!Please select one or more rows to edit");
            return;
        } else {
            
            /**
             * We have to send a /deviceout[OSC] of the old values
             * and a /devicein[OSC] of the new one
             */
            int rowT = detectedTable_jt.getSelectedRow();
            String msg = "";
            
            newLog(0,"[EDIT SIMULATED DEVICE]Selected row index:"+rowT);
            
            // old values
            //newLog(0,"[EDIT SIMULATED DEVICE]Copying old values...");
            //String uuidO = detectedTable_jt.getValueAt(rowT,0).toString();
            //String fnameO = detectedTable_jt.getValueAt(rowT,1).toString();
                       
            // new values
            newLog(0,"[EDIT SIMULATED DEVICE]Copying new values...");
            String uuidN = getUUID();
            String fnameN = getFName();
           
            //newLog(0,"[EDIT SIMULATED DEVICE]Setting new values...");
            //detectedTable_jt.setValueAt(uuidN,rowT,0);
            //detectedTable_jt.setValueAt(fnameN,rowT,1);
            Vector namesEdited = new Vector();
            DiABluID editedDeviceID = new DiABluID(uuidN,fnameN);
            DiABluDevice editedDevice = new DiABluDevice (editedDeviceID);
            namesEdited.addElement(editedDevice);
                                
            /*
             * Update the /devicesList
             *
             */            
            dDevicesList = modelTOvector (detectedTable_jt.getModel());
            DBbc.sendNamesChanged(namesEdited,addr);
            DBbc.sendDeviceList(dDevicesList,addr);            
            newLog(0,"[EDIT SIMULATED DEVICES]Updating list /devicelist");
     
        }
        
    }//GEN-LAST:event_edit_jbActionPerformed


    private void add_jbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_jbActionPerformed
        
        // get the id values
        String uuidT = getUUID();
        String fnameT = getFName();
        DiABluID DBidT = new DiABluID(uuidT,fnameT);
        
        
        
        // create the Simulated DiABlu Device
        DiABluDevice DBdv = new DiABluDevice (DBidT,666,0,0);
        
        // simulated status
        DBdv.setStatus(0);
        
        
        // add it to the internal table
        //addDevice(DBdv);
                
        // get the target address
        InetSocketAddress addr = getSocketAddress();                
                
        // Send the info on the new device
        Vector dDeviceList = new Vector();
        dDeviceList.addElement(DBdv);
        DBbc.sendAddDevices(dDeviceList,addr);
        newLog(0,"[ADD SIMULATED DEVICE][OSC /devicein]: "+uuidT+" | "+fnameT);
        
        // update the device count                       
        int dc = detectedTable_jt.getRowCount();                    
        DBbc.sendDeviceCount(dc,addr);                
        newLog(0,"[ADD SIMULATED DEVICE][OSC /devicecount]:"+ dc );
               
    }//GEN-LAST:event_add_jbActionPerformed
            
    private void credits_jmiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_credits_jmiActionPerformed
    // TODO add your handling code here:
       new DiABluCR(new javax.swing.JFrame(), true).setVisible(true);         
    }//GEN-LAST:event_credits_jmiActionPerformed

    private void exit_jmiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exit_jmiActionPerformed
    // TODO add your handling code here:
       System.exit(0);
    }//GEN-LAST:event_exit_jmiActionPerformed

    private void exit_jmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exit_jmActionPerformed
    // TODO add your handling code here:

    }//GEN-LAST:event_exit_jmActionPerformed

    private void about_jmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_about_jmActionPerformed
    // TODO add your handling code here:
     
    }//GEN-LAST:event_about_jmActionPerformed
 
    /**
     * Interface Methods
     */
    
    // INWatcher
    
    /**
     * this method is deprecated
     *
     */
    public void newDeviceList (Vector newDeviceList){
    
        if (newDeviceList==null||newDeviceList.size()==0){
            newLog(3,"newDeviceList() in DiABluUI has received an empty vector!!");
            return;
        }
        
        newLog(0,"[DiABluUI-newDeviceList()]A new device list with "+
                newDeviceList.size()+"elements has entered the GUI");
        // empty the previous list
        //detectedTable_jt.removeAll();
        // fill it up with the new values
        // TODO: method vectorTOmodel in order to populate an entire screen list
        //addDevices(newDeviceList);
    }
    
    public void newMsg (DiABluMsg newMsg){
    
    }
    
    public void newKey (DiABluKey newKey){
        
        
    
    }
    
    /**
     * Prints Strings in the LOG Text Area
     * DEPRECATED - use a priority
     */
    public void newLog (String newTextLog){
        
        if (log_jta.getLineCount()>1000){
            log_jta.setText("");
        }
        log_jta.append(newTextLog+"\n");
    }
    
    /**
     * Prints Strings in the LOG Text Area
     * Gives a different treatment according to the error priority
     *
     */
    public void newLog (int priority, String newLog){
        
        //TODO:Include a checker in order to clear the log from time to time
        /**
         * QUICK FIX - Simply clears the log when it reaches 1000lines
         * just to check the memory stamp
         */
        
        // get the desired log 
        String logType = (String) comboLog.getSelectedItem();                
        if (logType.equalsIgnoreCase("Simple") && priority==4) return;
        if (logType.equalsIgnoreCase("Errors only") && priority!=3) return;                
        
        if (log_jta.getLineCount()>1000){
            log_jta.setText("");
        }        
        
        // get the Time
        Calendar timeStamp = Calendar.getInstance();
        String dayLog = new Integer(timeStamp.get(Calendar.DAY_OF_MONTH)).toString();
        String monthLog = new Integer(timeStamp.get(Calendar.MONTH)+1).toString();
        String yearLog = new Integer(timeStamp.get(Calendar.YEAR)).toString();
        String hourLog = new Integer(timeStamp.get(Calendar.HOUR_OF_DAY)).toString();
        String minuteLog = new Integer(timeStamp.get(Calendar.MINUTE)).toString();
        String secondLog = new Integer(timeStamp.get(Calendar.SECOND)).toString();
        String timeLog = "["+dayLog+"/"+monthLog+"/"+yearLog+"@"+hourLog+":"+minuteLog+":"+secondLog+"]";
        
        // concatenate the message based on the priority
        switch (priority) {
            
            // Simple information
            case 0:
            {
                log_jta.append(timeLog+"[Simple Info]"+newLog+"\n");
                break;
            }
            
            // Input Validation Error
            case 1:
            {
                log_jta.append(timeLog+"[Input Error]"+newLog+"\n");
                break;
            }
            
            // Communications Error
            case 2:
            {
                log_jta.append(timeLog+"[Communications Error]"+newLog+"\n");
                break;
            }
            
            // Serious Error.Exception found
            case 3:
            {
                log_jta.append(timeLog+"[Serious Error!!]"+newLog+"\n");
                break;
            }
            
            // Detailed Info
            case 4:
            {
                log_jta.append(timeLog+"[Detailed Info]"+newLog+"\n");
                break;
            }
            
            // Security Error
            case 5:
            {
                log_jta.append(timeLog+"[Security Error]"+newLog+"\n");
                break;
            }
                
            default:
            {
                log_jta.append(timeLog+"[??Error!]"+newLog+"\n");
            }
        }
        
    }
    
    // OUTWatcher        
    // Forward the methods parameters to DB Business Code
    public void sendAddDevices(Vector aDevices, InetSocketAddress addr){
        
        DBbc.sendAddDevices(aDevices,addr);
    }
    
    public void sendRemoveDevices(Vector rDevices, InetSocketAddress addr){
        DBbc.sendRemoveDevices(rDevices,addr);
    }
    
    public void sendDeviceList(Vector lDevices, InetSocketAddress addr){
        DBbc.sendDeviceList(lDevices,addr);
    }
        
    public void sendMsg(DiABluMsg newDMsg, InetSocketAddress addr){
        DBbc.sendMsg(newDMsg,addr);
    }
    
    public void sendKeys(DiABluKey newDKey, InetSocketAddress addr){
        DBbc.sendKeys(newDKey,addr);
    }
    
    public void sendDeviceCount(int dCount, InetSocketAddress addr){
        DBbc.sendDeviceCount(dCount,addr);
    }
    
    
    public void sendNamesChanged(Vector nDevices, InetSocketAddress addr) {
        DBbc.sendNamesChanged(nDevices,addr);
    }
     
    // Local getter & setter methods
    
    // UUID
    /**
     * Sets the UUID in the GUI
     */
    private void setUUID (String newUUID) {
    
        uuid_jtf.setText(newUUID);
    }
    
    /**
     * Returns the UUID present in the GUI
     */
    private String getUUID() {
       
        return uuid_jtf.getText();
    }
    
    // Friendly Name's
    /**
     * Sets the Friendly Name of the simulated device
     */
    private void setFName (String fName){
        
         friendly_jtf.setText(fName);
    }  
    
    /**
     * Sets the Friendly Name of the simulated device
     */
    private String getFName(){
        
        return friendly_jtf.getText();
    }
    
    public int getBTdelay() {
        
        String buf = delay_jtf.getText();
        int delay = 10000;
        
        try {
              delay = Integer.parseInt(buf);
              return delay;
              
        } catch (NumberFormatException nfe) {
            
            newLog(1,"Delay factor is not a number!Returning default delay("+DEFAULT_DELAY+")");
            return DEFAULT_DELAY;
            
        }
        
    }
    
    // Message
  
    // GameAction
    private void setGAction(String gAction){
    
    }
    
    private String getGAction () {
        
        String gaT = gaction_jcb.getSelectedItem().toString();
        newLog(0,"[SIMULATED MESSAGING]Game Action Pressed:"+gaT);
        return  gaT;
       
    }
    
    // KeyPressed
    /**
     * Sets the Key pressed of the simulated device
     * WARNING!:This method accepts a STRING not a code
     */
    private void setKeyPressed (String keyPressed){
        // TODO:method
         //key_jtf.setText(keyPressed);
    }
    
    /**
     * Gets the Key pressed of the simulated device
     * WARNING!:This method returns a STRING not a code
     */
    private String getKeyPressed () {
    
        String keyT = key_jcb.getSelectedItem().toString();
        newLog(0,"[SIMULATED MESSAGING]Key Pressed:"+keyT);
        return  keyT;
       
    }
    
    /**
     *  MessageIn get & set
     */
    private DiABluMsg getTextMessage () {
        
        // Info & Debug Log
        newLog(0,"[getTextMessage][Assembling a DiABlu Message...]");
        
        // Construct the DiABlu ID of the sender
        String sendersUUID = getUUID();
        String sendersFName = getFName();        
        DiABluID sendersID = new DiABluID(sendersUUID,sendersFName);
        
        // get the senders message
        String sendersMsg = messagein_jtf.getText();
        
        // Create & Assemble a DiABlu Message
        DiABluMsg newMessageIn = new DiABluMsg(sendersID, sendersMsg);
        
        return newMessageIn;
    }
    
    // This method is never called
    // TODO: print a log exception
    private void setTextMessage (String nmsg){
        
        messagein_jtf.setText(nmsg);
    }
    
    // Settings
    
    // Service
    /**
     * Sets the DiABlu's Server Service Name
     */
    private void setServiceName (String newServiceName) {
        
        service_jtf.setText(newServiceName);
    }
    
    /**
     * Returns the DiABlu's Server Service Name & desc
     */
    public String getServiceName () {
        
        return service_jtf.getText();
    }
    
    public String getServiceDescription() {
        
        return serviceDesc_jtf.getText();
        
    }
    
    
    // Target Address
    /**
     * Sets the DiABlu's Server Target Address
     */
    private void setTargetAddress (String newTargetAddress){
        
        adress_jtf.setText(newTargetAddress);
    }
    
    /**
     * Gets the DiABlu's Server Target Address
     */
    public String getTargetAddress() {
        
        return adress_jtf.getText();
    } 
    
    public InetSocketAddress getSocketAddress()
    {
        String socketstr = getTargetAddress();
        int idx = getPort();
        InetSocketAddress tempAddr = new InetSocketAddress (socketstr, idx); 
        return tempAddr;
    }
        
    // Port
    private void setPort (int newPort){
        
        // Convert Int to String and set the field
        String newSPort = new Integer(newPort).toString();
        port_jtf.setText(newSPort);
        
    }
    
    private int getPort () {
        
        String tempSPort = port_jtf.getText();     
        int tempIPort = new Integer(tempSPort.trim()).intValue();
        return tempIPort;
        
    }
    
    public Vector getDiABluList(){
        
        // get our current list (TableModel)
        TableModel tableModelList = detectedTable_jt.getModel();
        
        // convert the TableModel into a Vector of DiABluDevices
        Vector DiABluList = modelTOvector(tableModelList);
        
        // return the vector with the DiABluDevices
        return DiABluList;
        
    }
   
    
    public void addDevice(DiABluDevice newDD) {
        
        // get the info on the device
        String uuidT = newDD.getID().getUUID();
        String fnameT = newDD.getID().getFName();
        String deviceT = newDD.getStringDevice();
        //String statusT = newDD.getStringStatus();
                        
        newLog(0,"[DiABluUI-addDevice()]UUID:"+uuidT+"|FNAME:"+fnameT);
        DefaultTableModel modelT = (DefaultTableModel) detectedTable_jt.getModel();
        
        modelT.addRow(new Object[] { uuidT, fnameT, deviceT, "" });
        //newLog(0,"[DiABluUI-addDevice()]Updating table...");
        detectedTable_jt.setModel( (TableModel) modelT );        
        
    }
    
    
    
    public void addDevices(Vector diabluList) {
        
        // Paranoid check for null pointers
        if (diabluList==null||diabluList.size()==0) {
            newLog(3,"addDevices() Method in DiABluUI has been called with empty arg");
            return;
        }
        
        for (int i=0;i<diabluList.size();i++){
            
            addDevice((DiABluDevice)diabluList.elementAt(i));
        }
        
        
    }
    
    public void removeDevices(Vector diabluList){
        
        DiABluDevice currentDevice = null;                            // temporary diablu device        
        DefaultTableModel currentTable = (DefaultTableModel)          // get our current data table
                                         detectedTable_jt.getModel();  
        int locatedRow = -1;                                          // table index of target 
                                                                      // element, -1 means element 
                                                                      // not found
        int topList;                                                  // size of the arg list
        
        // Paranoid check for null pointers
        if (diabluList==null||diabluList.size()==0) {
            newLog(3,"removeDevices() Method in DiABluUI has been called with empty arg");
            return;
        }
        
        topList = diabluList.size();        
        for (int i=0;i<topList;i++) {
            
            currentDevice = (DiABluDevice) diabluList.elementAt(i);
            
            locatedRow = locateDevice(currentDevice.getID().getUUID());
            
            // if We've found a match let's remove the device            
            if (locatedRow!=-1) {
                
                newLog(0,"[DiABluUI-removing device @"+locatedRow); 
                // remove the row
                currentTable.removeRow(locatedRow);    
                // update the table
                detectedTable_jt.setModel( (TableModel) currentTable );                         
            }
        }     
      }
    
    /**
     * This method receives an list of DiABluDevices, compare's it 
     * with our current tablemodel and update's the tablemodel information
     *
     */
    public void editDevices(Vector diabluList){
        
        DiABluDevice currentDevice = null;
        DefaultTableModel currentTable = (DefaultTableModel) detectedTable_jt.getModel();  // get our current data table
        int locatedRow = -1; // table index of target element, -1 means element not found
        Object uuidO = null;
        Object fname0 = null;
        Object dtype0 = null;
        Object lastm0 = null;
        Object lastk0 = null;

        // TODO:last key & last msg fields of diabludevice
        
        // Paranoid check for null pointers
        if (diabluList==null) {
            
            newLog(3,"[DiABluUI-editDevices()] Method has been called with empty arg");
            return;
        }                                        
                
        for (int i=0;i<diabluList.size();i++) {
                        
            // get the device
            currentDevice = (DiABluDevice) diabluList.elementAt(i);
            
            // try to locate the device
            locatedRow = locateDevice(currentDevice.getID().getUUID());
                      
            if (locatedRow!=-1)    {
                
                // we've located the device
                // let's get it's values'
                uuidO = (Object) currentDevice.getID().getUUID();
                fname0 = (Object) currentDevice.getID().getFName();
         
                
                newLog(4,"[DiABluUI-editDevices()]Found changed name device @"+locatedRow);
                // We've found a match let's edit the device info   
                currentTable.setValueAt(uuidO,locatedRow,0);
                currentTable.setValueAt(fname0,locatedRow,1);        
                
                 // update the table
                detectedTable_jt.setModel( (TableModel) currentTable );  
            } else {
                
                newLog(1,"[DiABluUI-editDevices()]Device not found!! @"+locatedRow);
            }
            
        }  
        
    }
    
    /*
     * This method receives a DiABluDevice locates it in the tablemodel 
     * and updates it's information
     * WARNING:This method uses the input UUID as a primary key
     *
     */
    public void editDevice(DiABluDevice dd){
        
        newLog(4,"Locating device:"+dd.toString());
        int locatedRow = locateDevice(dd.getID().getUUID());
        
        // make sure i've got work to do'
        if (locatedRow!=-1) {
           
           newLog(4,"Device located @"+locatedRow);
           // get the Device's info'
           Object fname0 = (Object) dd.getID().getFName();
           Object dtype0 = (Object) dd.getStringDevice();
           Object lastm0 = (Object) dd.getLastMessage();
           Object lastk0 = (Object) dd.getLastKey();
           
           // get & set the current tablemodel
           DefaultTableModel currentTable = (DefaultTableModel) detectedTable_jt.getModel();
           currentTable.setValueAt(fname0,locatedRow,1);
           currentTable.setValueAt(dtype0,locatedRow,2);
           currentTable.setValueAt(lastm0,locatedRow,3);
           currentTable.setValueAt(lastk0,locatedRow,4);
           
           // update the table
           detectedTable_jt.setModel( (TableModel) currentTable );  
           
        }
        newLog(4,"Device not locatized!");
        
    }
    
    /**
     * This method returns the tablemodel index of the first device found
     * with the given uuid
     *
     */
    public int locateDevice(String targetUUID) {
        
        newLog(4,"[DiABluUI-locateDevice()]Target uuid:"+targetUUID);
        int i;                                          // temporary counter                                    
        DefaultTableModel buffer = (DefaultTableModel) detectedTable_jt.getModel();    // our current data table        
        String tempUUID = "";                               // temporary uuid used to compare
        int top = buffer.getRowCount();                     // total of table rows
        
        // Check for an empty model
        if (top==0) return -1;
                    
        // get the first element
        //tempUUID = buffer.getValueAt(i,0).toString();
        
        // do a cicle until we find our target
        for (i=0;i<top;i++){
            tempUUID = buffer.getValueAt(i,0).toString();
            if (tempUUID.equalsIgnoreCase(targetUUID)) break;
        }
        
        //check our results
        if (i==top) {
            
            // element not found
            newLog(4,"[DiABluUI-locateDevice()]Device:"+targetUUID+"not found");
            return -1;
        } else {
            
            // we've found a match, let's return the index
            newLog(4,"[DiABluUI-locateDevice()]Device:"+targetUUID+"found at index:"+i);
            return i;
        }
        
    }           
    
    
    /*
     *  This method returns the friendly name of a present device
     *  It checks the tablemodel for the device returns "" if no device found.
     */
    public String getDeviceFName(String id) {
        
        
        int index = locateDevice(id);
        
        if (index!=-1) {
            
            // we've found the device let's get the name'
            DefaultTableModel buffer = (DefaultTableModel) detectedTable_jt.getModel();    // our current data table
            String fn = buffer.getValueAt(index,2).toString();    
            return fn;
            
        }         
        // no device found
        return "";
    }
    
    /*
     *  This method accepts an id and a msg and updates the table model "last message" columm
     */
    public void updateLastMsg(DiABluMsg dm) {
        
        String idT = dm.getID().getUUID();
        int index = locateDevice(idT);
        
        if (index !=-1) {
            
            // we've found the device let's update the table model'
            DefaultTableModel buffer = (DefaultTableModel) detectedTable_jt.getModel();    // our current data table
            buffer.setValueAt(dm.getText(),index,3);
            
            // update the table
            detectedTable_jt.setModel( (TableModel) buffer );                                                                        
            
        }
                                       
    }
    
    /*
     * updates the last key/msg field in the table
     *
     */
    public void updateLastKey(DiABluKey dk){
        
        String idT = dk.getID().getUUID();
        int index = locateDevice(idT);
        
        if (index !=-1) {
            
            // we've found the device let's update the table model'
            DefaultTableModel buffer = (DefaultTableModel) detectedTable_jt.getModel();    // our current data table
            buffer.setValueAt(dk.toString(),index,4);
            
            // update the table
            detectedTable_jt.setModel( (TableModel) buffer );                                                                        
            
        }                
        
    }
    
    /**
     * Converts a tablemodel object into a Vector of DiABlu Devices
     */
    public Vector modelTOvector ( TableModel temp ) {
        
        Vector diABluList = new Vector();
        int nRows = temp.getRowCount();
        DiABluID DBidT = null;
        DiABluDevice DBdvT = null;
        String uuidT = "";
        String fnameT = "";
        String statusT1 = "";
        int statusT2;
                
        // Convert each line into a DiABluDevice Object and add it to the vector
        for ( int i=0; i < nRows; i++ ) {
            
            // get the DiABluID
            uuidT = temp.getValueAt(i,0).toString();
            fnameT = temp.getValueAt(i,1).toString();
            DBidT = new DiABluID(uuidT,fnameT);
            
            // get the status
            statusT1 = temp.getValueAt(i,2).toString();
            if ( statusT1.equalsIgnoreCase("Simulated") ){ 
                statusT2 = 0; 
            } else { 
                statusT2 = 1;
            }
            
            // Create & Add the DiABlu Device to the Vector
            DBdvT = new DiABluDevice (DBidT,statusT2);
            diABluList.addElement(DBdvT);
        
        }
         
        return diABluList;
        
    }

    
    /** 
     *  Sends the list of present devices
     *
     */
    
    
    /**
     * @param args the command line arguments
     *
    public static void main(String args[]) {
        // TODO: Parse the ARGS
        // TODO: Put a help situation /?
        
        java.awt.EventQueue.invokeLater(new Runnable() {
        
            public void run() {
                new DiABluUI().setVisible(true);
            }
        });
    }
    */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu about_jm;
    private javax.swing.JButton add_jb;
    private javax.swing.JLabel adress_jl;
    private javax.swing.JTextField adress_jtf;
    private javax.swing.JButton clearLog_jb;
    private javax.swing.JComboBox comboLog;
    private javax.swing.JMenuItem credits_jmi;
    private javax.swing.JLabel delay_jl;
    private javax.swing.JTextField delay_jtf;
    private javax.swing.JTable detectedTable_jt;
    private javax.swing.JPanel detected_jp;
    private javax.swing.JButton edit_jb;
    private javax.swing.JMenu exit_jm;
    private javax.swing.JMenuItem exit_jmi;
    private javax.swing.JLabel friendly_jl;
    private javax.swing.JTextField friendly_jtf;
    private javax.swing.JComboBox gaction_jcb;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox key_jcb;
    private javax.swing.JLabel logDetail_jl;
    private javax.swing.JPanel log_jp;
    private javax.swing.JScrollPane log_jsp;
    private javax.swing.JTextArea log_jta;
    private javax.swing.JMenuBar menubar_jmb;
    private javax.swing.JLabel message_jl;
    private javax.swing.JTextField messagein_jtf;
    private javax.swing.JLabel port_jl;
    private javax.swing.JTextField port_jtf;
    private javax.swing.JButton remove_jb;
    private javax.swing.JButton sendKeys_jb;
    private javax.swing.JButton sendTextMsg_jb;
    private javax.swing.JLabel service_jl;
    private javax.swing.JTextField service_jtf;
    private javax.swing.JPanel settings_jp;
    private javax.swing.JPanel sim_jp;
    private javax.swing.JLabel uuid_jl;
    private javax.swing.JTextField uuid_jtf;
    // End of variables declaration//GEN-END:variables
    
}
